<template>
  <div id="item-bank-import" class="jx-content" :class="{'isCreativeCourse':isCreativeCourse}">
    <!-- 预览弹出框 -->
    <el-dialog :close-on-click-modal="false" width="850" class="dialog-questions" title="试题预览" :visible.sync="dialogQuestion">
      <div class="dialog-content markdown-body">
        <div class="question-title" v-html="rowData.content"></div>
        <div v-if="rowData.questionType === 1" v-for="(item,index) in rowData.answer" :key="index" class="question-chose">
          <span>{{ answerChose[index] }}：</span>
          <span class="question-flex" v-html="item.content"></span>
        </div>
        <div class="question-answer">答案：
          <span v-if="rowData.questionType === 3" class="chose" style="font-family:'黑体';font-size:16px;" v-html="answerTrue"></span>
          <span v-else class="chose" v-html="answerTrue"></span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="button-style" @click="dialogQuestion = false">确 定</el-button>
      </span>
    </el-dialog>
    <div>
      <el-tabs v-model="activeName" @tab-click="tabHandleClick">
        <el-tab-pane name="first" v-if="choseTableData">
          <span slot="label">
            <el-badge ref="tableTabs" :hidden="!choseTableData.length" :value="getChoseTableDataLength()" class="item">选择题目</el-badge>
          </span>
          <div class="search-box">
            <el-form :inline="true" ref="searchForm" :model="searchForm">
              <!-- <el-form-item label="关键词">
                <el-input v-model="searchForm.name"></el-input>
              </el-form-item> -->
              <el-form-item label="课程 :" v-if="courseAndChapterSelect">
                <el-cascader :clearable="true" change-on-select :props="cascaderconfig" :options="courseAndChapterSelect" v-model="selectedOptions" @change="courseAndChapterSelectChange">
                </el-cascader>
              </el-form-item>
              <el-form-item label="题目类型 :">
                <el-select :clearable="true" v-model="questionTypeMessage" placeholder="请选择" @change="getTopicModel">
                  <el-option v-for="(item,index) in questionTypeList" :key="index" :label="item.message" :value="item.type"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <div @click="getList" class="button-style">搜 索</div>
              </el-form-item>
            </el-form>
          </div>
          <el-table ref="tableData" :data="tableData" @selection-change="handleSelectionChange" style="width: 100%" v-show="activeName === 'first'">
            <el-table-column :selectable='checkboxT' disabled="true" type="selection" width="55"></el-table-column>
            <el-table-column label="试题题目">
              <template slot-scope="scope">
                <div :title="delHTMLLabel(scope.row.content)" style="text-align:left;" class="question-content-timu beyond-hiding" v-html="delHTMLLabel(scope.row.content)"></div>
              </template>
            </el-table-column>
            <el-table-column prop="questionTypeMessage" label="题目类型" width="180"></el-table-column>
            <el-table-column prop="courseName" label="课程" width="180"></el-table-column>
            <el-table-column prop="chapterName" label="章节"></el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
              <template slot-scope="scope">
                <div class="table-button">
                  <el-button @click="dialogQuestionShow(scope.row)" type="text" size="small">预览</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane class="second" label="已选择" name="second">
          <div class="search-box">
            <el-form :inline="true" ref="searchForm" :model="searchForm" label-width="80px">
              <el-form-item>
                <div class="button-style" @click="choseDel">删 除</div>
              </el-form-item>
            </el-form>
          </div>
          <el-table ref="choseTableData" :data="choseTableData" @selection-change="choseHandleSelectionChange" style="width: 100%" v-show="activeName === 'second'">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="试题题目">
              <template slot-scope="scope">
                <div :title="delHTMLLabel(scope.row.content)" style="text-align:left;" class="question-content-timu beyond-hiding" v-html="delHTMLLabel(scope.row.content)"></div>
              </template>
            </el-table-column>
            <el-table-column prop="questionTypeMessage" label="题目类型" width="180"></el-table-column>
            <el-table-column prop="courseName" label="课程" width="180"></el-table-column>
            <el-table-column prop="chapterName" label="章节"></el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
              <template slot-scope="scope">
                <div class="table-button">
                  <el-button @click="dialogQuestionShow(scope.row)" type="text" size="small">预览</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="btn-group">
      <button @click="submitQuestion" class="button-style question-submit">保存</button>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import $ from "jquery";
export default {
  data() {
    return {
      //是否是创作课程页面下
      isCreativeCourse: true,
      searchForm: {
        //关键词
        keyWord: "",
        //课程id
        courseId: "",
        //章节id
        chapterId: "",
        //题型序号
        questionType: ""
      },
      //课程和章节级联select
      courseAndChapterSelect: "",
      //课程和章节级联选中
      selectedOptions: [],
      //级联设置
      cascaderconfig: {
        value: "id"
      },

      //题目类型名称
      questionTypeMessage: "",
      //题目类型数组
      questionTypeList: [],
      //提交数组
      choseIds: [],
      //试题预览
      dialogQuestion: false,
      activeName: "first",
      tableData: [],
      choseTableData: [],
      delChoseTableData: [],
      //table弹出层
      rowData: "",
      //试题答案选项
      answerChose: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],
      //试题正确答案
      answerTrue: "",
      //删除试题id数组
      delQuestionList: []
    };
  },
  created() {
    //验证页面是不是创建课程的页面
    let currentPath = this.$router.history.current.path;
    if (currentPath.match("CreativeCourse")) {
      this.isCreativeCourse = true;
    } else {
      this.isCreativeCourse = false;
    }
    //CreativeCourse
    console.log(this.$router.history.current.path, 66666);
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.getList();
      this.addRowIndex();
      this.getTopicSelected();
      this.getCourseAndChapterSelect();
      this.reGetChapter();
    },
    delHTMLLabel(str) {
      let reg = /<[^>]*>|<\/[^>]*>/gm;
      let result = str.replace(reg, "");
      return result;
    },
    getChoseTableDataLength() {
      let that = this;
      that.$nextTick(function() {
        //console.log(that.$refs.tableTabs.$el.childNodes[1]);
        let el = that.$refs.tableTabs.$el.childNodes[1];
        if (that.choseTableData.length) {
          el.style.display = "block";
        } else {
          el.style.display = "none";
        }
        el.innerHTML = that.choseTableData.length;
      });
      return that.choseTableData.length;
    },
    reGetChapter() {
      let self = this;
      self.$http
        .get(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/chapter/list/owner"
        )
        .then(response => {
          let res = response.data;
          if (res.code == "200") {
            self.$nextTick(() => {
              //self.tableData = res.data;
            });
            //已经有章节,判断导航显示
            self.$parent.mark = false;
            self.$parent.chaperFlag = false;
          } else if (res.code == "404") {
            //self.tableData = "";
            //暂无章节,判断导航显隐藏
            this.$parent.mark = true;
            this.$parent.chaperFlag = false;
          }
        })
        .catch(err => {
          self.$message.error(res.message);
        });
    },
    //选中行不双向绑定
    //复选框禁选
    checkboxT(row, index) {
      if (!row.used) {
        return 1;
      } else {
        return 0;
      }
    },
    //点击预览按钮
    dialogQuestionShow(row) {
      this.dialogQuestion = true;
      console.log(row);
      this.rowData = row;
      //添加答案

      let answer = row.answer;
      this.answerTrue = "";
      //选择题
      if (row.questionType === 1) {
        //遍历找出正确答案选项
        for (let x in answer) {
          console.log(answer[x].isCorrect);
          if (answer[x].isCorrect) {
            this.answerTrue += this.answerChose[x];
          }
        }
      }
      //判断题
      if (row.questionType === 2) {
        if (answer[0].isCorrect) {
          this.answerTrue = "正确";
        } else {
          this.answerTrue = "错误";
        }
      }
      //填空题
      if (row.questionType === 3) {
        this.answerTrue = answer[0].content;
      }
    },
    //保存提交
    submitQuestion() {
      let that = this;
      let choseTableData = that.choseTableData;
      let arrIds = [];
      $.each(choseTableData, function(i, d) {
        arrIds.push(d.id);
      });
      console.log(arrIds);
      axios
        .post(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/1/question-repository/import-from-preset",
          arrIds
        )
        .then(function(res) {
          console.log("成功1");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              that.$message({
                message: "添加成功",
                type: "success"
              });
              that.$router.push({ path: "ItemBankList" });
            } else {
              that.$message({
                message: res.data.message,
                type: "error"
              });
            }
          }
        })
        .catch(function(err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    //获取列表
    getList() {
      var that = this;
      axios
        .get(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/1/question-repository/preset",
          {
            params: that.searchForm
          }
        )
        .then(function(res) {
          console.log("成功1");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              let questionList = res.data.data;
              //填空题替换(+)为（）
              $.each(questionList, function(i, d) {
                if (d.questionType === 3) {
                  let str = d.content;
                  var result = str.replace(/\(\+\)/g, "（）"); //把(+)替换成()
                  d.content = result;
                }
              });
              that.tableData = questionList;
              console.log(that.tableData, 22222);
            }
          }
        })
        .catch(function(err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    addRowIndex() {
      let tableData = this.tableData;
      $.each(tableData, function(i, d) {
        d.index = i;
      });
      //console.log(tableData);
    },
    handleSizeChange() {},
    handleCurrentChange() {},
    //选择题目-checkbox
    handleSelectionChange(val) {
      this.choseTableData = val;
      console.log(this.choseTableData, 112233);
    },
    //已选择-checkbox
    choseHandleSelectionChange(val) {
      this.delChoseTableData = val;
    },
    //已选择-删除
    choseDel() {
      let that = this;
      //选中数组
      let delChoseTableData = this.delChoseTableData;
      console.log(delChoseTableData);
      if (!delChoseTableData.length) {
        that.$message({
          message: "请选择要删除的内容",
          type: "warning"
        });
        return;
      }
      that
        .$confirm("是否删除选中?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          //取消选中
          that.closeRowSelection(delChoseTableData);
          that.$message({
            message: "删除成功",
            type: "success"
          });
        })
        .catch(() => {});
    },
    //取消选中，传对象数组
    closeRowSelection(rows) {
      console.log(rows);
      if (rows) {
        rows.forEach(row => {
          console.log(row);
          this.$refs.tableData.toggleRowSelection(row, false);
        });
      } else {
        this.$refs.tableData.clearSelection();
      }
    },
    //已选择-取消选择
    toggleSelection(rows) {
      // if (rows) {
      //   rows.forEach(row => {
      //     this.$refs.multipleTable.toggleRowSelection(row);
      //   });
      // } else {
      //   this.$refs.multipleTable.clearSelection();
      // }
    },
    tabHandleClick(tab, event) {
      console.log(tab, event);
    },
    //获取题目类型
    getTopicModel(val) {
      this.searchForm.questionType = val;
    },
    //获取题目类型和章节下拉
    getTopicSelected() {
      var that = this;
      axios
        .get(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/1/question-repository/dropdown-list"
        )
        .then(function(res) {
          console.log("成功");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              console.log(res.message);
              //赋值题目类型
              let questionTypeList = res.data.data.questionTypeList;
              that.questionTypeList = questionTypeList;
            }
          }
        })
        .catch(function(err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    //获取课程和章节下拉
    getCourseAndChapterSelect() {
      var that = this;
      axios
        .get(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/1/question-repository/course-chapter-list"
        )
        .then(function(res) {
          console.log("成功");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              that.courseAndChapterSelect = res.data.data;
              console.log(res.data.data, 1122334);
            }
          }
        })
        .catch(function(err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    courseAndChapterSelectChange(val) {
      if (val.length === 0) {
        this.searchForm.courseId = "";
        this.searchForm.chapterId = "";
      }
      if (val.length === 1) {
        this.searchForm.courseId = val[0];
        this.searchForm.chapterId = "";
      }
      if (val.length === 2) {
        this.searchForm.courseId = val[0];
        this.searchForm.chapterId = val[1];
      }
      console.log(this.searchForm, 123);
    }
  }
};
</script>
<style lang="scss" scoped>
@import "../../../styles/img-init";
</style>
<style lang="scss">
@import "../../../styles/layout/color_variables";
#item-bank-import.isCreativeCourse{
  margin: 20px auto 30px;
}
#item-bank-import {
  img {
    max-width: 80%;
  }
  width: 1200px;
  margin: 0px auto 30px;
  .el-cascader {
    line-height: 30px;
  }
  .btn-group {
    text-align: center;
    padding: 30px 0;
  }
  .dialog-import-questions {
    .dialog-content {
      text-align: left;
      padding: 20px 64px 0;
      .question-title {
        font-weight: bold;
        font-size: 16px;
        margin-bottom: 20px;
        p {
          line-height: 30px;
        }
      }
      .question-chose {
        font-size: 14px;
        line-height: 24px;
        padding: 6px 0;
        display: flex;
        .question-flex {
          flex: 1;
        }
      }
      .question-answer {
        font-size: 16px;
        .chose {
          font-size: 18px;
          color: #385899;
          vertical-align: -2px;
          p {
            line-height: 30px;
          }
        }
        margin-top: 20px;
      }
    }
    .el-dialog__footer {
      text-align: center;
    }
  }
  .el-badge__content {
    right: -10px;
    z-index: 1;
  }
  .el-tabs__nav-scroll {
    overflow: initial;
    &:after {
      content: "";
      display: block;
      clear: both;
    }
  }
  .el-tabs__nav-wrap {
    overflow: initial;
  }
  .el-tabs__nav-wrap::after {
    background: none;
  }
  .el-tabs__item {
    border: 1px solid #d9d9d9;
    padding: 0 20px;
    height: 40px;
    line-height: 40px;
    color: #474747;
  }
  .el-tabs__item.is-active {
    background: #1277eb;
    color: #fff;
  }
  .el-tabs__active-bar {
    background: none;
  }
  #tab-first {
    border-top-left-radius: 6px;
    border-bottom-left-radius: 6px;
  }
  #tab-second {
    position: relative;
    border-top-right-radius: 6px;
    border-bottom-right-radius: 6px;
    margin-left: -1px;
  }
  .second .search-box {
    text-align: right;
  }
  .sub {
    background-color: #f56c6c;
    border-radius: 10px;
    color: #fff;
    display: inline-block;
    font-size: 12px;
    height: 18px;
    line-height: 18px;
    padding: 0 6px;
    text-align: center;
    white-space: nowrap;
    border: 1px solid #fff;
    z-index: 9;
    transform: translate(170px, -9px);
    position: absolute;
  }
  .dialog-questions {
    .el-dialog__body {
      max-height: 500px;
      overflow: auto;
    }
    .dialog-content {
      padding: 20px 64px 0;
      .question-title {
        font-weight: bold;
        font-size: 16px;
        margin-bottom: 20px;
        p {
          line-height: 30px;
        }
      }
      .question-chose {
        font-size: 14px;
        line-height: 24px;
        padding: 6px 0;
        display: flex;
        .question-flex {
          flex: 1;
        }
        p {
          line-height: 24px;
        }
      }
                .question-answer {
        font-size: 16px;
        .chose {
          font-size: 18px;
          color: #385899;
          vertical-align: -2px;
          p {
            line-height: 30px;
          }
        }
        margin-top: 20px;
      }
    }
    .el-dialog__footer {
      text-align: center;
    }
  }
}
</style>
